<template>
<div class="search-suggestion">
    <!-- <van-button @click="btn">按钮</van-button> -->
    <van-cell @click="$emit('search')" icon="search" v-for="(item, index) in suggestList" :key="index" >
      <div v-html="heighLight(item)"></div>
     <!-- {{heighLight(item)}} -->
    </van-cell>
  </div>
</template>
           
<script>
import { getSearchSuggestions_api } from '@/api/search.js'
// import  _  from  "loadsh"   {debounce:function(){}}
// import  {debounce}  from  "loadsh"
// import { debounce } from 'lodash'
import { debounce } from 'lodash'
export default {
  props: ['searchVal'],
  data() {
    return {
      // num:1
      suggestList: []
    }
  },
  cretaed() {
    /* 
建议组件总共实现了三个功能
1、输入显示搜索结果
2、输入做防抖
3、输入对所有的结果显示高亮


    步骤分析：
    1、获取表单值
    2、监听表单值的改变，只要值发生改变就发送请求
    3、渲染数据到结构上

    */
  },
  methods: {
    // btn(){
    //   this.num++
    // }

    //  设置搜索建议结果值===所有的结果值  显示高亮
    heighLight(dataStr){
      //  dataStr= 1 or 1 == 1'
      // ======<span class='active'>1</span> or 1 == 1'
      // return dataStr.replace(this.searchVal,`<span class='active'>${this.searchVal}</span>`)   //     var   dataStr='hello world'  
      var  reg=new  RegExp(this.searchVal,'gi')
       return dataStr.replace(reg,`<span class='active'>${this.searchVal}</span>`)   //     var   dataStr='hello world'   
    },

    //  点击搜索列表显示搜索结果页面并且显示数据
    // ff(){
    //   this.$emit('search')
    // }
  },
  watch: {
    // num(newVal,oldVal){
    //   console.log(newVal,oldVal,666777);
    // },

    searchVal: {
      /* 
      handler  函数名字不能更改
      immediate: true   //   // 该回调将会在侦听开始之后被立即调用
      */
      // handler: async function(newVal, oldVal) {
      //   //console.log(newVal,oldVal,33333222222);
      //   const { data: res } = await getSearchSuggestions_api(newVal)
      //   console.log(res, 44444)
      //   this.suggestList = res.data.options
      // },

      //  防抖写法
      //handler: async function(newVal, oldVal) {
      handler: debounce(async function(newVal, oldVal) {
        //console.log(newVal,oldVal,33333222222);
        const { data: res } = await getSearchSuggestions_api(newVal)
        console.log(res, 44444)
        this.suggestList = res.data.options
      }, 300),
      immediate: true //   // 该回调将会在侦听开始之后被立即调用
    },

    
  
  }
}
</script>
<style scoped  lang='less'>
.search-suggestion{
  /deep/.active{
    color:red;
  }
}
</style>